package com.twenty.seven.apollo.demo.netty;

public class PipelineDemo {

    public HandlerChainContext head = new HandlerChainContext(new AbstractHandler() {
        @Override
        void doHandler(HandlerChainContext chainContext, Object object) {
            chainContext.runNext(object);
        }
    });
    public void requestProcess(Object object){
        this.head.handler(object);
    }
    public void addLast(AbstractHandler handler){
        HandlerChainContext context = head;
        while(context.next != null){
            context = context.next;
        }
        context.next = new HandlerChainContext(handler);
    }

    public static void main(String[] args) {
        PipelineDemo pipelineDemo = new PipelineDemo();
        pipelineDemo.addLast(new Handler1());
        pipelineDemo.addLast(new Handler2());
        pipelineDemo.addLast(new Handler1());
        pipelineDemo.addLast(new Handler2());
        pipelineDemo.requestProcess("火车呜呜呜呜&&");
    }

}
class HandlerChainContext{
    HandlerChainContext next;
    AbstractHandler handler;
    public HandlerChainContext(AbstractHandler handler){
        this.handler = handler;
    }
    void handler(Object arg0){
        this.handler.doHandler(this,arg0);
    }

    void runNext(Object object){
        if(this.next != null){
            this.next.handler(object);
        }
    }
}

abstract class AbstractHandler{
    abstract void doHandler(HandlerChainContext chainContext,Object object);
}

class Handler1 extends AbstractHandler{

    @Override
    void doHandler(HandlerChainContext chainContext, Object object) {
        object = object.toString()+"..handler1的小尾巴";
        System.out.println("我是handler1的实例，我在处理"+object);
        chainContext.runNext(object);
    }
}

class Handler2 extends AbstractHandler{

    @Override
    void doHandler(HandlerChainContext chainContext, Object object) {
        object = object.toString()+"..handler2的小尾巴";
        System.out.println("我是handler2的实例，我在处理"+object);
        chainContext.runNext(object);
    }
}